package com.icangya.admin;

import com.alibaba.fastjson.JSONObject;
import com.icangya.Utils.JSONUtils;
import com.icangya.Utils.UploadUtils;
import com.icangya.Value.FootBall;
import com.icangya.domain.AdvertClick;
import com.icangya.domain.AdvertRecord;
import com.icangya.domain.User;
import com.icangya.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import static com.icangya.Value.FootBall.ADVERT_ROW;

@CrossOrigin
@RestController
@RequestMapping(path = "/foot/advert/")
public class AdvertController {

    @Autowired
    private IAdvertService iAdvertService;
    @Autowired
    private IMoneyService iMoneyService;
    @Autowired
    private IMissionService iMissionService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 添加广告信息
     *
     */
    @RequestMapping(value = "setAdvertRecord" )
    public @ResponseBody JSONObject addAdvertRecord(HttpServletRequest request,HttpSession session,
                                              @RequestParam(value = "fileUrl[]",required = false,defaultValue = "") String[] fileUrl,@RequestParam int status,
                                                    @RequestParam double advertMoney, @RequestParam double advertTopMoney, @RequestParam String advertContent) {

        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);

        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
        String openId=user.getOpenId();
//              String openId="oyGuGwmC8IJb1Y2GfOz7Zd0xA9Cc";
        if(advertMoney > 0.6){
            return null;
        }
        if (advertMoney <= 0.1){
            return null;
        }
        if(advertMoney >2){
            return null;
        }
        boolean bool= iAdvertService.checkAdvertMoney(openId,advertTopMoney,status);
            if(bool) {
                //上传的目录地址
//                String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
                String path="upload/";
                String[] imgUrl = new String[fileUrl.length];

                if (fileUrl != null) {
                    for (int i = 0; i < fileUrl.length; i++) {
                        imgUrl[i]= UploadUtils.upload(request,fileUrl[i],path);
                        logger.info("广告图片的路径==================="+imgUrl[i]);
//                        String strpath = GetImage.getWeixinImg(fileUrl[i], uploadDir);
//                        String[] str = strpath.split("/");
//                        imgUrl[i] = "upload/" + str[str.length - 1];
                    }
                }
                Timestamp now = new Timestamp(new Date().getTime());
                //status   0:游戏币  1：赠送广告金
                AdvertRecord ar = new AdvertRecord(openId, advertMoney, advertTopMoney, now, now, advertContent, 0);
                ar.setRealPageView(0L);
                ar.setShamPageView(0L);
                AdvertRecord advertRecord = iAdvertService.addAdvertRecord(ar, imgUrl, status);//添加这条广告信息
                if (advertRecord != null) {
                        //判断是否领取任务
                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            //User user,long missionId,IMissionService iMissionService
                           UploadUtils.missionUtil(user,1,iMissionService);
                        }
                    }).start();

                    return JSONUtils.getRoot(0, "success", "发布成功");
                }
                return JSONUtils.getRoot(1, "fail", "发布失败");
            }
        return JSONUtils.getRoot(1, "fail", "发布失败");
    }


    /**
     *检查用户的广告费是否充足
     * @param session
     * @param advertTopMoney
     * @param status  //选择的广告费是游戏币还是赠送广告金
     * @return
     */
    @RequestMapping("checkAdvertMoney")
    public JSONObject checkAdvertMoney(HttpSession session,@RequestParam double advertTopMoney,@RequestParam int status){

        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        logger.info("checkAdvert=====status"+status);
        if(status==0 || status==1){
            if(user == null){
                return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
            }
        String openId=user.getOpenId();
//            String openId="oyGuGwmC8IJb1Y2GfOz7Zd0xA9Cc";
            //status   0:游戏币  1：赠送广告金
            //前端传入的金额不能高于用户的广告费
            boolean check=  iAdvertService.checkAdvertMoney(openId,advertTopMoney,status);
            if(check)
                return JSONUtils.getRoot(0,"success",null);
            return JSONUtils.getRoot(1,"fail","用户广告金不足");
        }else{
            return JSONUtils.getRoot(1,"fail","广告金类型有误");
        }


    }


    /**
     * 检查用户是否可以查看广告
     * @param session
     * @return
     */
    @RequestMapping(value = "checkLookAdvert")
    public JSONObject checkLookAdvert(HttpSession session,HttpServletRequest request,HttpServletResponse response){

        //用户未充值不能查看广告
        //用户每天12点之后未充值不能查看广告
        User user =  (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
        boolean bool=iMoneyService.getRechargeRecord(user.getOpenId());
//        boolean bool=iMoneyService.getRechargeRecord("oyGuGwmC8IJb1Y2GfOz7Zd0xA9Cc");
        if(bool) {
            return JSONUtils.getRoot(0, "success", null);
        }
        return JSONUtils.getRoot(1,"fail","请充值后，查看广告");
    }


    /**
     * 点击广告时存储用户点击广告的记录
     *@param advertId 广告编号Id
     */
    @RequestMapping(value="setClickAdvert")
    public synchronized JSONObject addAdvertClick(HttpSession session,@RequestParam long advertId){


        User user =  (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
//      String openId="oyGuGwmC8IJb1Y2GfOz7Zd0xA9Cc";

        String openId= user.getOpenId() ;
        AdvertRecord advertRecord = iAdvertService.getAdvertRecord(advertId);
        try {
            if(advertRecord.getOpenId().equals(openId)){
                return JSONUtils.getRoot(3,"fail",null);
            }
        }catch (NullPointerException e){
            logger.info("advertRecord.getOpenId():"+advertRecord.getOpenId()+"===openId:"+openId);
        }


        boolean bool=  iAdvertService.checkAdvertByOpenId(openId,advertId);

        //用户点击该广告的记录不存在，就添加记录
        if(bool){
            AdvertClick advertClick=new AdvertClick();
            advertClick.setOpenId(openId);
            advertClick.setAdvertId(advertId);
            advertClick.setClickMoney(advertRecord.getAdvertMoney());
            advertClick.setClickTime(new Timestamp(new Date().getTime()));
            AdvertClick ad= iAdvertService.addAdvertClick(advertClick);
            if(ad==null)
                return JSONUtils.getRoot(2,"fail","广告费官方赠送");
            return JSONUtils.getRoot(0,"success",ad);
        }

        return JSONUtils.getRoot(1,"fail","该广告已查看");

    }

    /**
     *查询单个用户用户发布广告的记录
     * */

    @RequestMapping(value="getAdvertAll")
    public JSONObject getAdvertAll(HttpSession session){
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openId= user.getOpenId() ;
//      String openId="oxn-ruOzhsoIxfGd8-vdp-JBeZWs";
        return JSONUtils.getRoot(0,"success", iAdvertService.getAdvertAll(openId));
    }

    /**
     * 修改用户发布广告的广告金额
     * @param id
     * @param money
     * @return
     */
    @RequestMapping(value = "updateAdvertTopMoney")
    public JSONObject updateAdvertTopMoney(@RequestParam  long id,@RequestParam double money){

        boolean bool= iAdvertService.updateAdvertMoney(id,money);
        if(bool)//修改成功  返回code=0
            return JSONUtils.getRoot(0,"success", null);
        return JSONUtils.getRoot(1,"fail", "您输入的金额超过您的余额或者追加金额不足");
    }

    /**
     * 查询单条广告信息
     * @param advertId
     * @return
     */
    @RequestMapping(value = "getAdvertById",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getAdvertById( @RequestParam  long advertId){

        logger.info("advertId==================="+advertId);
       JSONObject jsonObject= iAdvertService.getAdvertById(advertId);
        if(jsonObject!=null)//修改成功  返回code=0
            return JSONUtils.getRoot(0,"success", jsonObject);
        return JSONUtils.getRoot(1,"fail", null);
    }

    /**
     * 查询所有用户发布的广告信息  前端一页3条
     * @return
     */
    @RequestMapping(value="getAdvert")
    public JSONObject getAdvert(HttpSession session,@RequestParam int startPage){

        logger.info(startPage+"............页码");
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openid=user.getOpenId();
        JSONObject object=iAdvertService.getAdvertNotClick(openid,startPage);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("notValue",null);
        jsonObject.put("value", null);

        if(object!=null) {
            jsonObject.put("notValue",object);
            return JSONUtils.getRoot(0, "success", jsonObject);
        }

        if(object==null ){
            JSONObject obj=iAdvertService.getAdvertNotClick(openid,1);
//            JSONObject obj=null;
                if(obj==null){
                    jsonObject.put("value", iAdvertService.getAdvert(startPage,ADVERT_ROW));
                    return JSONUtils.getRoot(0, "success", jsonObject);
                }
        }
        return JSONUtils.getRoot(1,"faild", null);

    }

    /**
     * 查询所有用户发布的广告信息  前端
     * @return
     */
//    @RequestMapping(value="getAdvertAllMessage",method = RequestMethod.GET)
    public JSONObject getAdvertAll(HttpSession session,@RequestParam int startPage){
        if("".equals(startPage) || startPage < 0){
            return JSONUtils.getRoot(1,"faild", null);
        }
        logger.info(startPage+"............已阅Advert页码");
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openid=user.getOpenId();
        JSONObject jsonObject= iAdvertService.getAdvert(startPage,ADVERT_ROW);
        if(jsonObject!=null)
            return JSONUtils.getRoot(0,"success", jsonObject);
        return JSONUtils.getRoot(1,"faild", null);

    }

    /**
     * 查询前一千条
     * @return
     */
    @RequestMapping(value="getAdvertRecordShame")
    public JSONObject getAdvertRecordShame(){
       List list= iAdvertService.getAdvertRecordShame();
        if(list!=null)
            return JSONUtils.getRoot(0,"success", list);
        return JSONUtils.getRoot(1,"faild", null);
    }

}


















